<?php

namespace App\Http\Controllers\Admin;

use App\DTOS\Admin\RoleDTO;
use App\Http\Controllers\Controller;
use App\Models\Role;
use App\Services\AuthorityService;
use App\Services\RoleService;
use App\Utils\MyLog;
use App\Utils\ResponseUtil;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Spatie\Permission\Models\Permission;

class RoleController extends Controller
{
    private RoleService $roleService;
    private Request $request;
    private AuthorityService $authorityService;

    public function __construct(RoleService $roleService,Request $request,AuthorityService $authorityService)
    {
        $this->roleService = $roleService;
        $this->request = $request;
        $this->authorityService = $authorityService;
    }

    public function add()
    {
        $data = $this->request->only('name');
        $this->roleService->add($data);
        return ResponseUtil::success();
    }
    public function paginate()
    {
        $dto = new RoleDTO($this->request->only('name'));
        $paginate = $this->roleService->paginate($dto);
        return ResponseUtil::paginate($paginate);
    }
    public function edit($id)
    {
        $data = $this->request->only('name');
        $this->roleService->updateById($id,$data);
        return ResponseUtil::success();
    }

    public function detail($id)
    {
        $role = Role::query()->with('permissions')->find($id);
        $role['permissionIds'] = $role->permissions->pluck('id')->toArray();
        MyLog::info('权限组信息'.json_encode($role));
        $role['allPermissions'] = Permission::all();
        return ResponseUtil::success($role);
    }

    public function delete($id)
    {
        DB::beginTransaction(); //验证数据完整性: model_has_roles role_has_permissions
        try {
            Role::query()->where('id',$id)->delete();
            DB::select("DELETE FROM model_has_roles WHERE role_id={$id}");
            DB::select("DELETE FROM role_has_permissions WHERE role_id={$id}");
            DB::commit();
            return ResponseUtil::success();
        }catch (\Exception $e){
            DB::rollBack();
            return ResponseUtil::error($e->getMessage());
        }
    }

    public function givePermission($id){ //分配权限
        $data = $this->request->only('permissionIds');
        MyLog::info('插入的配置权限明细'.json_encode($data));
        $permissionIds = data_get($data,'permissionIds',[]);
        $role = Role::query()->find($id);
        MyLog::info('d对应用户信息'.json_encode($role));
        $role->syncPermissions(Permission::query()->whereIn('id',$permissionIds)->get());
        $this->authorityService->refreshPermission();
        return ResponseUtil::success();
    }

}
